package com.tzstcl.archetype.cms.web;

import com.tzstcl.commons.utils.UploadFileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;

/**
 * 公司：天筑科技股份有限公司
 * 作者：dingyz
 * 日期：2019年07月16日
 * 说明：ckeditor图片上传
 */
@Controller
@RequestMapping("/profile")
public class CkController {


    @Value("${ck.http}")
    private String ck_http;

    @RequestMapping(value = "/ckUpload")
    public void ckedtorImageUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {

        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

        String path = null;

        if (commonsMultipartResolver != null) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile mfile = multiRequest.getFile(iter.next());
                String type = "ckimage";
                Map<String, Object> map = UploadFileUtil.saveFile(mfile, type);
                  path =ck_http+ map.get("fileUrl");
                System.out.println("path="+path);
            }
        }

        response.setContentType("text/html;charset=UTF-8");
        String callback = request.getParameter("CKEditorFuncNum");
        try {
            PrintWriter out = response.getWriter();
            out.print("<script type=\"text/javascript\">");
            out.print("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" +path.replaceAll("\\\\","/") + "',''" + ")");
            out.print("</script>");
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
